import axios from 'axios';
import { ElMessage } from 'element-plus'
import {useAdminUserStore} from "@/store/adminUser.js";
import { useRouter } from 'vue-router'

const mode = import.meta.env.VITE_APP_MODE
const baseURL = import.meta.env.VITE_APP_API_URL
console.log(111, import.meta.env)

const AxiosInstance = axios.create({
    baseURL: baseURL,
    timeout: 5000
})

AxiosInstance.interceptors.request.use(config => {
    const adminUserStore = useAdminUserStore()
    if (adminUserStore.tokenInfo != null) {
        config.headers[adminUserStore.tokenInfo.tokenName] = adminUserStore.tokenInfo.tokenValue
    }
    return config;
}, error => {
    return Promise.reject(error);
})

AxiosInstance.interceptors.response.use(resp => {
    if (resp.status === 200) {
        const responseData = resp.data
        if (responseData.code === 0) {
            return responseData
        } else {
            ElMessage.error(responseData.message)
            if (responseData.code === 3002) {
                const sysUserStore = useAdminUserStore()
                sysUserStore.clearToken()
                const router = useRouter()
                router.replace({path: "/login"})
            }
            return Promise.reject(new Error(responseData.message))
        }
    }
}, error => {
    if (error.code === 'ERR_NETWORK') {
        ElMessage.error("服务异常，请稍后再试!")
    } else {
        ElMessage.error("未知异常，请稍后再试!")
    }
    return Promise.reject(error);
})

/**
 * Http Get请求
 * @param url
 * @param query
 * @returns {Promise<axios.AxiosResponse<any>>}
 * @constructor
 */
export const HttpGet = (url, query={}) => {
    if (mode === 'static') {
        return Promise.reject().catch(() => {})
    } else {
        return AxiosInstance.get(url, {
            params: query
        }).then((resp) => { return resp })
            .catch(() => {})
    }
}

/**
 * Http Post请求
 * @param url
 * @param data
 * @returns {Promise<axios.AxiosResponse<any>>}
 * @constructor
 */
export const HttpPost = (url, data={}) => {
    if (mode === 'static') {
        return Promise.reject().catch(() => {})
    } else {
        return AxiosInstance.post(url, data, {})
            .then((resp) => {
                return resp
            })
    }
}

/**
 * 文件上传
 * @param url 请求地址
 * @param file 上传文件对象
 * @param config 请求配置
 * @returns {Promise<axios.AxiosResponse<any>>}
 * @constructor
 */
export const HttpUpload = (url, file, config = {}) => {
    const formData = new FormData()
    formData.append('file', file)

    if (mode === 'static') {
        return Promise.reject().catch(() => {})
    } else {
        return AxiosInstance.post(url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
            ...config
        }).then(resp => {
            return resp
        }).catch(() => {
            this.$message.error('文件上传时发生错误')
        })
    }
}

/**
 * 文件下载
 * @param url 请求地址
 * @param data 请求体
 * @param filename 下载文件名称
 * @param config 请求配置
 * @constructor
 */
export const HttpDownload = (url, data, filename, config = {}) => {
    if (mode === 'static') {
        return Promise.reject().catch(() => {})
    } else {
        AxiosInstance.post(url, data, {
            ...config,
            responseType: 'blob'
        }).then(resp => {
            const link = document.createElement('a');
            const blob = new Blob([resp]);
            link.href = URL.createObjectURL(blob);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
        })
    }
}

export default AxiosInstance;
